package com.exam.stu.exam.business;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.exam.base.business.AbstractBusiness;
import com.exam.base.model.ResponsePageModel;
import com.exam.base.service.IAbstractService;
import com.exam.base.util.ServletBeanTools;
import com.exam.stu.exam.model.AnswerTopic;
import com.exam.stu.exam.model.ChoiceTopic;
import com.exam.stu.exam.model.JudgementTopic;
import com.exam.stu.exam.model.TbExamPaper;
import com.exam.stu.exam.model.TbTopicPaper;
import com.exam.stu.exam.model.TbTopics;
import com.exam.stu.exam.model.TypeCount;
import com.exam.stu.exam.service.TbExamPaperService;
import com.exam.stu.exam.service.TbTopicPaperService;
import com.exam.stu.power.model.TbBtn;
import com.exam.stu.topic.model.TbTopic;
import com.exam.stu.topic.service.TbTopicService;

@Service("topicPaperBussiness")
public class TopicPaperBussiness  extends AbstractBusiness<TbTopicPaper> {

	@Autowired
	private TbTopicPaperService tbTopicPaperService;
	@Autowired
	private TbExamPaperService examPaperService;

	@Autowired
	private TbTopicService tbTopicService;
	
	@Override
	protected IAbstractService<TbTopicPaper> getBaseService() { 
		return tbTopicPaperService;
	}
	/**
	 * 获取用户表格数据
	 * @param request
	 * @return
	 */
	public ResponsePageModel<TbTopicPaper> getTopicPaperPageData(HttpServletRequest request) {
		try {

			TbTopicPaper queryModel = ServletBeanTools
					.populate(TbTopicPaper.class, request); 
			return this.getPageData(queryModel);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	
	
	  public List<TbTopics> addTbTopicPaper(String id,HttpServletRequest request) {
		  try {
			    List<TbTopics> listData = new ArrayList<TbTopics>();
				ChoiceTopic choice = ServletBeanTools.populate(ChoiceTopic.class, request);				
				TbTopics choiceTopic = new TbTopics();				
				if(choice.isHasData()&&choice.getChoiceNumber()>0) {
				choiceTopic.setType(choice.getChoicType());;
				choiceTopic.setTbTopicPaper(getChoice( id,choice));			
				choiceTopic.setHasData(true);
				}
				listData.add(choiceTopic);
				JudgementTopic judgement = ServletBeanTools.populate(JudgementTopic.class, request);	
				TbTopics judgementTopic = new TbTopics();
				if(judgement.isHasData()&&judgement.getJudgementNumber()>0) {
				judgementTopic.setType(judgement.getJudgementType());;
				judgementTopic.setTbTopicPaper(getJudgment( id,judgement));
				judgementTopic.setHasData(true);
				}
				listData.add(judgementTopic);
				AnswerTopic answer = ServletBeanTools.populate(AnswerTopic.class, request);	
				TbTopics answerTopic = new TbTopics();
				if(answer.isHasData()&&answer.getAnswerNumber()>0) {
				answerTopic.setType(answer.getAnswerType());;
				answerTopic.setTbTopicPaper(getAnswer( id,answer));
				answerTopic.setHasData(true);
				}
				listData.add(answerTopic);	
				return listData;
			} catch (Exception e) {
				e.printStackTrace();
			}
		  
		  return null;
	  } 
	 
	 
	/**
	 * 随机取组卷试题
	 * @param request
	 * @throws Exception 
	 * @return
	 */
	public List<TbTopic> getTbTopicPaper(String type, int number,String grade)throws Exception{		
		TbTopic tbTopic = new TbTopic();
		tbTopic.setType(type);
		if(!grade.isEmpty()) {
		tbTopic.setGrade(grade);
		}
		List<TbTopic> listTopic = new ArrayList<TbTopic>();		
		int count = tbTopicService.queryCount(tbTopic);
		if (count < number)
		 {
			throw new Exception("试题数量超出！");
		}else{
		List<TbTopic> lstTopic = tbTopicService.queryList(tbTopic);
		Collections.shuffle(lstTopic);
		  for(int i=0 ; i < number; i++) {			 
			listTopic.add(lstTopic.get(i));				 				
		  } 
		}
		  return listTopic;
	}
	/**
	 * 创建组卷选择试题表
	 * @param request
	 * @return
	 * @throws Exception 
	 */
	public List<TbTopicPaper> getChoice(String id,ChoiceTopic topic) throws Exception{	
		try {
			int random = topic.getChoiceRandom();
			int low = topic.getChoiceLow();
			int medium = topic.getChoiceMedium();
			int issue = topic.getChoiceIssue();
			int score = topic.getChoiceScore();
			int total = topic.getChoiceNumber();		
		TbTopic tbTopic = new TbTopic();		
		tbTopic.setType(topic.getChoicType());
		int count = tbTopicService.queryCount(tbTopic);
		if(total > count) {
			throw new Exception("试题数量超出！");
		}			
		List<TbTopicPaper> tbTopicPaper = new ArrayList<TbTopicPaper>();
		if(random > 0) {			
			
			String randomGrade = "";
			List<TbTopicPaper> topicPaper1 = addTbTopicPaper(random,score,id,topic.getChoicType(),randomGrade);
			for(TbTopicPaper topicPaper : topicPaper1) {
				tbTopicPaper.add(topicPaper);
			}				
		}
		if(low> 0) {			
			
			String lowGrade = "低";
			List<TbTopicPaper>topicPaper2 = addTbTopicPaper(low,score,id,topic.getChoicType(),lowGrade);
			for(TbTopicPaper topicPaper : topicPaper2) {
				tbTopicPaper.add(topicPaper);
			}	
		}
		if(medium > 0) {			
			
			String mediumGrade = "一般";
			List<TbTopicPaper> topicPaper3 = addTbTopicPaper(medium,score,id,topic.getChoicType(),mediumGrade);
			for(TbTopicPaper topicPaper : topicPaper3) {
				tbTopicPaper.add(topicPaper);
			}
	
		}
		if(issue > 0) {
			
			String issueGrade = "高";
			List<TbTopicPaper> topicPaper4 = addTbTopicPaper(issue,score,id,topic.getChoicType(),issueGrade);
			for(TbTopicPaper topicPaper : topicPaper4) {
				tbTopicPaper.add(topicPaper);
			}
		}
		
		List<TbTopicPaper> listData = judgementRepeat( tbTopicPaper, topic.getChoicType());
		Collections.shuffle(listData);
		int i = 1;
		for(TbTopicPaper topicPaper : listData) {
			topicPaper.setIntSerial(i);
			i++;
		}
		tbTopicPaperService.batchAdd(listData);		
		listData = paperOf(listData);
		return listData;

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		return null;
	}	
	/**
	 * 随机添加试题
	 * @param request
	 * @return
	 * @throws Exception 
	 */
	public List<TbTopicPaper> addTbTopicPaper(int number,int score,String id,String type,String grade) throws Exception{	
		try {
			
		if(number < 0) {
			return null;
		}else {		
		
		List<TbTopicPaper> listTopicPaper = new ArrayList<TbTopicPaper>();		
		List<TbTopic> listTopic = getTbTopicPaper(type,number,grade);		
		for(TbTopic topic : listTopic) {
			TbTopicPaper tbTopicPaper = new TbTopicPaper();
		    tbTopicPaper.setTopics(topic); 
			tbTopicPaper.setPaperId(id);
			tbTopicPaper.setType(type);
			tbTopicPaper.setValue(score);
			tbTopicPaper.setTopic(topic.getContent());
			tbTopicPaper.setAnswer(topic.getResult());
			tbTopicPaper.setTopicId(topic.getId());
			listTopicPaper.add(tbTopicPaper);
		}
		
		return judgementRepeat(listTopicPaper,type);
		}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 判断是否试题重复
	 * @param request
	 * @return	
	 */
	public List<TbTopicPaper> judgementRepeat(List<TbTopicPaper> listTopicPaper,String type) throws Exception{	
		try {
			for(int i= 0;i < listTopicPaper.size()-1;i++) {
					for(int j= i+1;j < listTopicPaper.size();j++) {
					if(listTopicPaper.get(i).getTopicId().equals(listTopicPaper.get(j).getTopicId())) {
												 
						return judgementRepeat(updataTbTopicPaper(listTopicPaper, type,j),type);
					}				
			    }
			
			}			
			return listTopicPaper;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 更新重复试题
	 * @param request
	 * @return
	 * @throws Exception 
	 */
	public List<TbTopicPaper> updataTbTopicPaper(List<TbTopicPaper> listTopicPaper,String type,int x){
		TbTopic tbTopic = new TbTopic();
		tbTopic.setType(type);		
		List<TbTopic> lstTopic = tbTopicService.queryList(tbTopic);		  						 		
		for(TbTopicPaper topicPaper:listTopicPaper)
			for(int j= 0;j < lstTopic.size();j++) {
				if(topicPaper.getTopicId()==lstTopic.get(j).getId())
			lstTopic.remove(j);
		}
		int count = lstTopic.size();
		int index=(int)(Math.random()*count);	
		lstTopic.get(index);
		listTopicPaper.get(x).setTopicId(lstTopic.get(index).getId());
		listTopicPaper.get(x).setTopic(lstTopic.get(index).getContent());
		listTopicPaper.get(x).setAnswer(lstTopic.get(index).getResult());
		
	    return listTopicPaper;
	}
	/**
	 * 创建组卷判断试题表
	 * @param request
	 * @return
	 * @throws Exception 
	 */
	
		public List<TbTopicPaper> getJudgment(String id,JudgementTopic topic) throws Exception{	
			try {
				int random = topic.getJudgementRandom();
				int low = topic.getJudgementLow();
				int medium = topic.getJudgementMedium();
				int issue = topic.getJudgementIssue();
				int score = topic.getJudgementScore();
				int total = topic.getJudgementNumber();		
			TbTopic tbTopic = new TbTopic();		
			tbTopic.setType(topic.getJudgementType());
			int count = tbTopicService.queryCount(tbTopic);
			if(total > count) {
				throw new Exception("试题数量超出！");
			}			
			List<TbTopicPaper> tbTopicPaper = new ArrayList<TbTopicPaper>();
			if(random > 0) {			
				
				String randomGrade = "";
				List<TbTopicPaper> topicPaper1 = addTbTopicPaper(random,score,id,topic.getJudgementType(),randomGrade);
				for(TbTopicPaper topicPaper : topicPaper1) {
					tbTopicPaper.add(topicPaper);
				}				
			}
			if(low> 0) {			
				
				String lowGrade = "低";
				List<TbTopicPaper>topicPaper2 = addTbTopicPaper(low,score,id,topic.getJudgementType(),lowGrade);
				for(TbTopicPaper topicPaper : topicPaper2) {
					tbTopicPaper.add(topicPaper);
				}	
			}
			if(medium > 0) {			
				
				String mediumGrade = "一般";
				List<TbTopicPaper> topicPaper3 = addTbTopicPaper(medium,score,id,topic.getJudgementType(),mediumGrade);
				for(TbTopicPaper topicPaper : topicPaper3) {
					tbTopicPaper.add(topicPaper);
				}
		
			}
			if(issue > 0) {
				
				String issueGrade = "高";
				List<TbTopicPaper> topicPaper4 = addTbTopicPaper(issue,score,id,topic.getJudgementType(),issueGrade);
				for(TbTopicPaper topicPaper : topicPaper4) {
					tbTopicPaper.add(topicPaper);
				}
			}
			
			List<TbTopicPaper> listData = judgementRepeat( tbTopicPaper, topic.getJudgementType());
			Collections.shuffle(listData);
			int i = 1;
			for(TbTopicPaper topicPaper : listData) {
				topicPaper.setIntSerial(i);
				i++;
			}
			tbTopicPaperService.batchAdd(listData);	
			listData = paperOf(listData);
			return listData;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
			return null;
		}	
	/**
	 * 创建组卷问答试题表
	 * @param request
	 * @return
	 * @throws Exception 
	 */
		public List<TbTopicPaper> getAnswer(String id,AnswerTopic topic) throws Exception{	
			try {
				int random = topic.getAnswerRandom();
				int low = topic.getAnswerLow();
				int medium = topic.getAnswerMedium();
				int issue = topic.getAnswerIssue();
				int score = topic.getAnswerScore();
				int total = topic.getAnswerNumber();		
			TbTopic tbTopic = new TbTopic();		
			tbTopic.setType(topic.getAnswerType());
			int count = tbTopicService.queryCount(tbTopic);
			if(total > count) {
				throw new Exception("试题数量超出！");
			}			
			List<TbTopicPaper> tbTopicPaper = new ArrayList<TbTopicPaper>();
			if(random > 0) {			
				
				String randomGrade = "";
				List<TbTopicPaper> topicPaper1 = addTbTopicPaper(random,score,id,topic.getAnswerType(),randomGrade);
				for(TbTopicPaper topicPaper : topicPaper1) {
					tbTopicPaper.add(topicPaper);
				}				
			}
			if(low> 0) {			
				
				String lowGrade = "低";
				List<TbTopicPaper>topicPaper2 = addTbTopicPaper(low,score,id,topic.getAnswerType(),lowGrade);
				for(TbTopicPaper topicPaper : topicPaper2) {
					tbTopicPaper.add(topicPaper);
				}	
			}
			if(medium > 0) {			
				
				String mediumGrade = "一般";
				List<TbTopicPaper> topicPaper3 = addTbTopicPaper(medium,score,id,topic.getAnswerType(),mediumGrade);
				for(TbTopicPaper topicPaper : topicPaper3) {
					tbTopicPaper.add(topicPaper);
				}
		
			}
			if(issue > 0) {
				
				String issueGrade = "高";
				List<TbTopicPaper> topicPaper4 = addTbTopicPaper(issue,score,id,topic.getAnswerType(),issueGrade);
				for(TbTopicPaper topicPaper : topicPaper4) {
					tbTopicPaper.add(topicPaper);
				}
			}
			List<TbTopicPaper> listData = judgementRepeat( tbTopicPaper, topic.getAnswerType());
			Collections.shuffle(listData);
			int i = 1;
			for(TbTopicPaper topicPaper : listData) {
				topicPaper.setIntSerial(i);
				i++;
			}
			tbTopicPaperService.batchAdd(listData);
			listData = paperOf(listData);
			return listData;
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
			return null;
		}	
	/**
	 * 获取试题信息
	 * @param userId
	 * @return
	 */
	public TbTopicPaper findByTopicPaperId(String id)
	{
		String topicId = tbTopicPaperService.findById(id).getTopicId();
		TbTopic topic = tbTopicService.findById(topicId);
		topic.setGradeUpdata(topic.getGrade());	
		if("选择题(单)".equals(topic.getType())) {
		topic.setTakeResult(topic.getResult());
		}
		TbTopicPaper  topicPaper = tbTopicPaperService.findById(id);
		topicPaper.setTopics(topic);
		
		return topicPaper;
	}
	/**
	 * 获取试题信息
	 * @param id
	 * @return
	 */
	public TbTopic findByTopicId(String id)
	{
		TbTopic topic= tbTopicService.findById(id);		
		topic.setGradeUpdata(topic.getGrade());	
		if("选择题(单)".equals(topic.getType())) {
		topic.setTakeResult(topic.getResult());
		}
		
		return topic;
	}
	/**
	 * 删除获取试题试卷信息
	 * @param userId
	 * @return
	 */
	public TbExamPaper examPaperFindByTopicPaperId(String id)
	{		
		String PaperId = tbTopicPaperService.findById(id).getPaperId();
		TbExamPaper paper = examPaperService.findById(PaperId);				
		return paper;
	}
	/**
	 * 加载获取试题试卷信息
	 * @param userId
	 * @return
	 */
	public TbExamPaper examPaperFindById(String id)
	{				
		TbExamPaper paper = examPaperService.findById(id);		
		
		return paper;
	}
	/**
	 * 获取试题试卷全部试题信息
	 * @param id
	 * @return
	 */
	public List<TbTopics> FindByPaperId(String id)
	{
		TbTopicPaper topicPaper = new TbTopicPaper();
		topicPaper.setPaperId(id);		
		List<TbTopicPaper> listData = tbTopicPaperService.queryList(topicPaper);		
		List<TbTopics> lisData = new ArrayList<TbTopics>();
		if(!listData.isEmpty()) {
		Map<String,List<TbTopicPaper>> btnMap = new HashMap<String, List<TbTopicPaper>>();
		for(TbTopicPaper paper : listData)	{
			String topicId = paper.getTopicId();
			TbTopic topic = tbTopicService.findById(topicId);
			paper.setTopics(topic);
			if(paper.getTopic()!=null) {
				if(paper.getTopic().length()>40) {
					paper.setTopic(paper.getTopic().substring(0, 37).concat("..."));
				}
					}
				if(paper.getAnswer()!=null) {
				if(paper.getAnswer().length()>20) {
					paper.setAnswer(paper.getAnswer().substring(0, 17).concat("..."));
				}
				}
			if(!btnMap.containsKey(paper.getType())) {
				btnMap.put(paper.getType(), new ArrayList<TbTopicPaper>());
			}
			   btnMap.get(paper.getType()).add(paper);
			
		}
		for(String key : btnMap.keySet()) {
			TbTopics topic = new TbTopics();
			topic.setType(key);
			List<TbTopicPaper> newList = sort(btnMap.get(key));
			topic.setTbTopicPaper(newList);
			topic.setHasData(true);
			lisData.add(topic);
		}
		}
		
		return lisData;
	}
	/**
	 * 试题排序
	 * @param List<TbTopicPaper>
	 * @return
	 */
	public List<TbTopicPaper> sort(List<TbTopicPaper> listdata){
		List<TbTopicPaper> newLisData = new ArrayList<TbTopicPaper>();
		if(listdata.size()>0) {
			for(int i= 1;i<listdata.size()+1;i++)
				for(TbTopicPaper topicPaper:listdata) {
					if(topicPaper.getSerial()==null) {
						int j = 1;
						for(TbTopicPaper topicPapers : listdata) {
							topicPapers.setIntSerial(j);
							j++;
						}
					}
					if(topicPaper.getIntSerial()==i) {
						newLisData.add(topicPaper);
					}
				}
			}
		return newLisData;
		}
	/**
	 * 题型排序
	 * @param List<TbTopicPaper>
	 * @return
	 */
	public List<TbTopics> sortType(List<TbTopics> listdata){		
		if(listdata.size()>0) {
			int x = 1 ;
				for(TbTopics topics:listdata) {
					if("选择题(单)".equals(topics.getType())) {
						topics.setTypeSort(x);
						x++;
					}
				}
				for(TbTopics topics:listdata) {
					if("判断题".equals(topics.getType())) {
						topics.setTypeSort(x);
						x++;
					}
				}				
				for(TbTopics topics:listdata) {
					if("问答题".equals(topics.getType())) {
						topics.setTypeSort(x);
					}
				}
		}
		return listdata;
		}

	/**
	 * 修改试题分值
	 * @param userId
	 * @return
	 */
	public void updataTopicP(String id,String value) {
		TbTopicPaper topicPaper=tbTopicPaperService.findById(id);
		int s = Integer.parseInt(value);
		topicPaper.setValue(s);
		tbTopicPaperService.update(topicPaper);
	}
	/**
	 * 修改试题分值
	 * @param userId
	 * @return
	 */
	public void updataTopics(String id,String value) {
		TbTopicPaper topicPaper=tbTopicPaperService.findById(id);
		String type = topicPaper.getType();
		String paperId=topicPaper.getPaperId();
		TbTopicPaper paper = new TbTopicPaper();
		int s = Integer.parseInt(value);
		paper.setPaperId(paperId);
		List<TbTopicPaper> listData=tbTopicPaperService.queryList(paper);
		for(TbTopicPaper papers : listData) {
			if(papers.getType().equals(type)) {
				papers.setValue(s);
			}
		}
		tbTopicPaperService.batchUpdate(listData);
	}
	/**
	 * 删除试题
	 * @param userId
	 * @return
	 */
	public void deletes(String id) {
		 TbTopicPaper topicPaper = tbTopicPaperService.findById(id);
		 TbTopicPaper paper = new  TbTopicPaper();
		 paper.setPaperId(topicPaper.getPaperId());
		 paper.setType(topicPaper.getType());
		 List<TbTopicPaper> listData = tbTopicPaperService.queryList(paper);
		 int  x = topicPaper.getIntSerial();
		 listData.remove(topicPaper);
		 for(TbTopicPaper topicP : listData) {			 
			 if(topicP.getIntSerial() > x) {
				 int i = topicP.getIntSerial()-1;
				 topicP.setIntSerial(i);
				
			 }	 
		 }
		tbTopicPaperService.delete(id);
		tbTopicPaperService.batchUpdate(listData);
	}
	/**
	 * 试题类型格式化
	 * @param userId
	 * @return
	 */
	public String typeOf(String type) {
		String types;
		if("1".equals(type)) {
			types ="选择题(单)";	
			return types;
		}else if("2".equals(type)) {
			types ="判断题"; 
			return types;
		}else if("3".equals(type)) {
			types ="问答题"; 
			return types;
		}
		return null;
	}
	/**
	 * 难度格式化
	 * @param userId
	 * @return
	 */
	public String gradeOf(String grade) {
		String grades;
		if("1".equals(grade)) {
			grades ="低";	
			return grades;
		}else if("2".equals(grade)) {
			grades ="一般"; 
			return grades;
		}else if("3".equals(grade)) {
			grades ="高"; 
			return grades;
		}
		return null;
	}
	/**
	 * 内容和答案的缩减格式化
	 * @param userId
	 * @return
	 */
	public ResponsePageModel<TbTopic> pageModelOf(ResponsePageModel<TbTopic> pageModel ) {
		List<TbTopic> listData = pageModel.getResultData();
		for(TbTopic topic : listData) {
			if(topic.getContent()!=null) {
		if(topic.getContent().length()>40)
			topic.setContent(topic.getContent().substring(0, 37).concat("..."));
			}
			if(topic.getResult()!=null) {
		if(topic.getResult().length()>40)
			topic.setSaveResult(topic.getResult().substring(0, 37).concat("..."));
		}
		}
		return pageModel;
	}
	/**
	 * 设置不同类型别选中的数量
	 * @param userId
	 * @return
	 */
	public TypeCount getCount(String id) {
		 TbTopicPaper  paper= new TbTopicPaper();
		 paper.setPaperId(id);
		 List<TbTopicPaper> listData =tbTopicPaperService.queryList(paper);
		 int a = 0;
		 int b = 0;
		 int c = 0;
		 for(TbTopicPaper topicPaper:listData) {
			if("选择题(单)".equals(topicPaper.getType())) {
				a++;
			}
			if("判断题".equals(topicPaper.getType())) {
				b++;
			}
			if("问答题".equals(topicPaper.getType())) {
				c++;
			}
		 }
		 TypeCount count = new TypeCount();
		 count.setChoiceCount(a);
		 count.setJudgementCount(b);
		 count.setAnserCount(c);
		 count.setHasData(true);
		return count;
	}
	/**
	 * 内容和答案的缩减格式化
	 * @param userId
	 * @return
	 */
	public List<TbTopicPaper> paperOf(List<TbTopicPaper> listData) {
	for(TbTopicPaper paper : listData) {
		if(paper.getTopic()!=null) {
		if(paper.getTopic().length()>40) {
			paper.setTopic(paper.getTopic().substring(0, 37).concat("..."));
		}
		}	
		if(paper.getAnswer()!=null) {
		if(paper.getAnswer().length()>20) {
			paper.setAnswer(paper.getAnswer().substring(0, 17).concat("..."));
		}
		}	
	}
	return listData;
	}
	
	
	
	
	
	
	
	
	
	
	}